﻿using B.S.Database.ErrorCode;
using B.S.Database.Write.Api.Application.Commands;
using B.S.Database.Write.Api.Application.Commands.Traceability;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Qiniu.Util;
using Qiniu.Storage;
using Microsoft.Extensions.Options;
using System.IO;
using System.Threading.Tasks;
using Qiniu.Http;
using B.S.Database.Write.Api.SysConfig;
using B.S.Database.Write.Api.Application.Commands.Slaughter;

namespace B.S.Database.Write.Api.Controllers
{
    /// <summary>
    /// 控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class ManagementController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<ManagementController> logger;

        public ManagementController(IMediator mediator, ILogger<ManagementController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }
        /// <summary>
        /// 溯源添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("traceability/create")]
        [AllowAnonymous]
        public  Task<Apiresult<object>> TraceabilityCreate(TraceabilityCreateCommands request)
        {
            return mediator.Send(request);
        }
        /// <summary>
        /// 账号注册
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("login/create")]
        [AllowAnonymous]
        public Task<Apiresult<object>> LoginCreate(LoginCreateCommands request)
        {
            return mediator.Send(request);
        }
        /// <summary>
        /// 逻辑删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("traceability/delete")]
        public Task<Apiresult<object>> TraceabilityDelete(TraceabilityDeleteCommands request)
        {
            return mediator.Send(request);
        }
        /// <summary>
        /// 批量逻辑删除
        /// </summary>
        /// <returns></returns>
        [HttpPost("traceability/batch-delete")]
        [AllowAnonymous]
        public Task<Apiresult<object>> BatchLogicalDeleteAsync([FromBody] TraceabilityBatchdeleteCommands request)
        {
            return mediator.Send(request);
        }
        /// <summary>
        /// 导出溯源数据为Excel
        /// </summary>
        /// <param name="traceabilityId">溯源ID</param>
        /// <param name="numberOfExports">导出数量</param>
        /// <returns></returns>
        [HttpGet("traceability/export")]
        [AllowAnonymous]
        public IActionResult ExportTraceability([FromServices] B.S.Database.Interface.Interface.IBaseResotity<B.S.Database.Domain.Entity.Basic_Traceability> traceabilityRepo, [FromQuery] int traceabilityId, [FromQuery] int numberOfExports)
        {
            var data = traceabilityRepo.GetAll().Where(x => !x.IsDelete && x.TraceabilityId == traceabilityId).Take(numberOfExports).ToList();
            // 生成Excel文件（这里只做简单CSV导出示例）
            var csv = "TraceabilityId,GoodsId,Production_Batch,Quality_Guarantee,Production_License,Manufacturing_Enterprise,Information_Completeness,NumberOfExports,Cover_Image,CreateName,CreateTime,UpdateName\n" + string.Join("\n", data.Select(d => $"{d.TraceabilityId},{d.GoodsId},{d.Production_Batch},{d.Quality_Guarantee},{d.Production_License},{d.Manufacturing_Enterprise},{d.Information_Completeness},{d.NumberOfExports},{d.Cover_Image},{d.CreateName},{d.CreateTime},{d.UpdateName}"));
            var bytes = System.Text.Encoding.UTF8.GetBytes(csv);
            return File(bytes, "text/csv", "TraceabilityExport.csv");
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns>
        [HttpPost("traceability/update")]
        [AllowAnonymous]
        public Task<Apiresult<object>> TraceabilityUpdate(TraceabilityUpdateCommands request)
        {
            return mediator.Send(request);
        }
        /// <summary>
        /// 多图片上传
        /// </summary>
        /// <param name="files">图片文件集合</param>
        /// <returns></returns>
        [HttpPost("upload-multiple-images")]
        [AllowAnonymous]
        public async Task<Apiresult<List<string>>> UploadMultipleImages([FromForm] IFormFileCollection files)
        {
            var res = new Apiresult<List<string>>();
            var imagePaths = new List<string>();
            
            try
            {
                if (files == null || files.Count == 0)
                {
                    res.Code = ApiEnums.失败;
                    res.Message = "请选择要上传的图片";
                    return res;
                }

                var uploadFolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", "images");
                if (!Directory.Exists(uploadFolder))
                {
                    Directory.CreateDirectory(uploadFolder);
                }

                foreach (var file in files)
                {
                    if (file.Length > 0)
                    {
                        // 生成唯一文件名
                        var fileName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
                        var filePath = Path.Combine(uploadFolder, fileName);
                        
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            await file.CopyToAsync(stream);
                        }
                        
                        // 保存相对路径
                        var relativePath = $"/uploads/images/{fileName}";
                        imagePaths.Add(relativePath);
                    }
                }

                res.Code = ApiEnums.成功;
                res.Message = "图片上传成功";
                res.Data = imagePaths;
            }
            catch (Exception ex)
            {
                res.Code = ApiEnums.失败;
                res.Message = $"图片上传失败: {ex.Message}";
            }
            
            return res;
        }
        /// <summary>
        /// 屠宰信息设置
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("SlaughterCreate")]
        [AllowAnonymous]
        public Task<Apiresult<object>> SlaughterCreate(SlaughterCreateCommands request)
        {
            return mediator.Send(request);
        }
        /// <summary>
        /// 企业信息设置
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("CompanyCreates")]
        [AllowAnonymous]
        public Task<Apiresult<object>> CompanyCreates(CompanyCreatesCommands request)
        {
            return mediator.Send(request);
        }
    }
}